package com.zhxin.nettylab.decoder.chapter2;

import com.zhxin.nettylab.decoder.chapter1.StringProcessHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * @ClassName NettyLineBasedDecoderDemo
 * @Description //LineBasedFrameDecoder 使用demo
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/12/7 0007 下午 4:05
 **/
public class NettyLineBasedDecoderDemo {
    private String s = "SingleZhang 学习Netty 笔记记录！";
    private String spliter = "\r\n";

    @Test
    public void testLineBasedFrameDecoder(){

        ChannelInitializer initializer = new ChannelInitializer<EmbeddedChannel>() {
            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {

                /*
                 * 添加流水线
                 * 先添加解码器
                 * 再添加业务流程处理器
                 * */
                ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new StringProcessHandler());
            }
        };

        EmbeddedChannel channel = new EmbeddedChannel(initializer);
        for(int i =0;i<100;i++){
            Random rd = new Random();
            int random =  rd.nextInt(3); //1-3之间随机数
            ByteBuf buffer = Unpooled.buffer();
            for(int j = 0;j<random;j++){
                buffer.writeBytes(s.getBytes(StandardCharsets.UTF_8)); // 往Buffer 写入数据
            }
            buffer.writeBytes(spliter.getBytes(StandardCharsets.UTF_8));

            channel.writeInbound(buffer); // 往Channel 写入 Buffer数据
        }


//        try{
//            Thread.sleep(Integer.MAX_VALUE);
//        }catch (InterruptedException e){
//            e.printStackTrace();
//        }
    }
}
